<?php
namespace App\Services;

use Config;
use App\Services\Openssl\QueryStockException;
use Log;

/**
* 商品在公共仓库存查询服务
*/
class QueryStock
{

    protected $config;
    protected $pubkey;

    function __construct()
    {

        $config = config('eorderinfo');
        $this->config = $config;

    }

    /** 设置参数
     * @param $key
     * @param $value
     */
    public function setParam($key,$value){
        $this->params[$key] = $value;
    }



    public function sendPost($goods_sn){

        $xmlorder = '<?xml version="1.0" encoding="utf-8"?>
                    <article>
                        <List>
                            <SEARCH_TYPE>1</SEARCH_TYPE>
                            <PALLETZONE>001</PALLETZONE>
                            <OWNER_NO>'. $this->config['owner_no'] .'</OWNER_NO>
                            <OWNER_ARTICLE_NO>' . $goods_sn . '</OWNER_ARTICLE_NO>
                        </List>
                    </article>';


        // echo $xmlorder;
        Log::info('查询仓库库存请求报文：'.$xmlorder);
        return $this->makeRequest($this->config['queryStock'], $xmlorder);
    }


    /**
     * 构建请求
     * @param $data
     * @return mixed|string
     */
    private function makeRequest($url, $data)
    {
        Log::info('查询仓库库存请求地址：'.$url);

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            // curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/xml; charset=utf-8"));
            // curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $response = curl_exec($ch);
            // echo $response;exit();
            Log::info('查询仓库库存响应信息：'.$response);


        }catch (\Exception $e){

            throw new QueryStockException($e->getMessage());
        }

        return $response;

        /*if ($response) {

            $response = str_replace('&', '&amp;', $response);
        }

        $repsonXmlObj = simplexml_load_string($response);

        if($repsonXmlObj->goods){


            $goods = (json_decode(json_encode($repsonXmlObj->goods),TRUE));

            $goodArray = [];
            foreach($goods as $k=>$v){
                // print_r ($v);
                if (isset($v['good_no'])){
                    $goodArray[$v['good_no']] = $v;

                }
            }

            return $goodArray;
        }
        else{

            throw new QueryStockException($repsonXmlObj->Detail);
        }*/



    }


}

?>